package com.jchao.auth.controller;

/**
 * create 2023/11/13 23:43
 */


import com.jchao.auth.service.SysUserService;
import com.jchao.common.config.exception.CustomException;
import com.jchao.common.jwt.JwtHelper;
import com.jchao.common.result.Result;
import com.jchao.common.utils.MD5;
import com.jchao.model.system.SysUser;
import com.jchao.vo.system.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 后台登录登出
 * </p>
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;


    /**
     * 登录
     *
     * @return
     */
    @PostMapping("login")
    @ApiOperation("登陆")
    public Result login(@RequestBody LoginVo loginVo) {
        SysUser user = sysUserService.getByUserName(loginVo.getUsername());
        if (user == null) {
            throw new CustomException(201, "用户不存在！");
        }
        String password = loginVo.getPassword();

        if (!MD5.encrypt(password).equals(user.getPassword())) {
            throw new CustomException(201, "密码错误！");
        }
        if (user.getStatus().equals(0)) {
            throw new CustomException(201, "用户被禁用！");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", JwtHelper.createToken(user.getId(), user.getUsername()));
        return Result.ok(map);

    }
    /**
     * 获取用户信息
     * @return
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("info")
    public Result info(HttpServletRequest request) {
        String username = JwtHelper.getUsername(request.getHeader("token"));
        Map<String, Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }
    /**
     * 退出
     * @return
     */
    @PostMapping("logout")
    public Result logout(){
        return Result.ok();
    }

}
